package cayte.xiami.in.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.RemoteException;
import cayte.xiami.in.AccountInfo;
import cayte.xiami.in.CheckinHandler;
import cayte.xiami.in.D;
import cayte.xiami.in.ad.PointManager;
import cayte.xiami.in.helper.Check;
import cayte.xiami.in.helper.DBHelper;
import cayte.xiami.in.helper.NetWorkHelper;
import cayte.xiami.in.helper.NotifyUtil;
import cayte.xiami.in.helper.SpfHelper;
import cayte.xiami.in.helper.SplashBgHelper;
import cayte.xiami.in.ui.CheckinActivity;

import com.umeng.analytics.MobclickAgent;

public class CheckinService extends Service implements Runnable {
	private static final String TAG = "CheckinService";

	private static final long SLEEP_TIME = 60 * 1000;
	private boolean isRun = false;

	private DBHelper dataBase = null;
	private CheckinHandler checkin = null;

	private final CheckinServiceAIDL.Stub mBinder = new CheckinServiceAIDL.Stub() {

		@Override
		public boolean isRun() throws RemoteException {
			// TODO Auto-generated method stub
			return isRun;
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return mBinder;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		isRun = true;
		D.d(TAG, "-----onCreate-----");

		dataBase = new DBHelper(this);
		checkin = new CheckinHandler(this);

		Thread thread = new Thread(this);
		thread.start();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (isRun) {
			if (D.OWNER ? checkTime4Owner() : checkTime()) {
				updateOnlintConfig();
				SpfHelper spf = new SpfHelper(this);
				// D.e("spf log : isAutoCheck is " + spf.isAutoCheck()
				// + " -- checkLastCheckDate is "
				// + spf.checkLastCheckDate());
				if (spf.isAutoCheck()) {
					if (spf.checkLastCheckDate()) {
						if (NetWorkHelper.isNetworkConnected(this)) {
							if (!Check.checkPunish(this)) {
								doCheckin();
							}
						}
					}
				}
			}
			D.sleep(SLEEP_TIME);
		}
	}

	private static final String KEY_SPF_FILE = "cayte_service";
	private static final String HOUR = "hour";
	private static final String MINUTES = "minutes";

	private boolean checkTime() {
		// TODO Auto-generated method stub.
		SharedPreferences spf = getSharedPreferences(KEY_SPF_FILE, 0);
		int hour = spf.getInt(HOUR, 2);
		int minutes = spf.getInt(MINUTES, 10);
		Date date = new Date();
		int h = date.getHours();
		int m = date.getMinutes();
		if (h == 0 && (m == 8 || m == 9)) {
			Random random = new Random();
			hour = random.nextInt(2);
			minutes = random.nextInt(60);
			if (hour == 0 && minutes < 20)
				minutes += 20;
			spf.edit().putInt(HOUR, hour).commit();
			spf.edit().putInt(MINUTES, minutes).commit();
		}
		if (h < hour)
			return false;
		if (h == hour && m < minutes)
			return false;
		return true;
	}

	private boolean checkTime4Owner() {
		// TODO Auto-generated method stub
		Date date = new Date();
		int h = date.getHours();
		int m = date.getMinutes();
		if (h == 0 && m < 10)
			return false;
		if (h == 23 && m > 50)
			return false;
		return true;
	}

	private int lastHour = -3;

	private void updateOnlintConfig() {
		// TODO Auto-generated method stub
		int curHour = new Date().getHours();
		if (curHour - lastHour >= 3) {
			MobclickAgent.updateOnlineConfig(this);
			lastHour = curHour;
			D.sleep(SLEEP_TIME);
			new SplashBgHelper(this).checkBg();
		}
	}

	private void doCheckin() {
		// TODO Auto-generated method stub
		D.e("CheckinService : Checkin Start");

		SpfHelper spf = new SpfHelper(this);
		PointManager pointsManager = PointManager.instance(this);

		ArrayList<AccountInfo> arr = dataBase.query();
		if (arr == null || arr.isEmpty())
			return;

		if (!D.OWNER) {
			if (arr.size() * Check.CHECK_POINT > pointsManager.queryPoints()) {
				spf.saveAutoCheck(false);
				D.e("CheckinService : points not enough , points is "
						+ pointsManager.queryPoints());
				NotifyUtil.showAutoCheck(this);
				return;
			}
		}

		ArrayList<AccountInfo> accs = new ArrayList<AccountInfo>();
		AccountInfo a = null;
		for (AccountInfo acc : arr) {
			a = checkin.check(acc);
			accs.add(a);
		}

		boolean success = true;
		for (AccountInfo acc : accs) {
			if (acc.state == CheckinHandler.SUCCESS) {
				dataBase.updataOne(acc);
				if (!D.OWNER)
					pointsManager.spendPoints(Check.CHECK_POINT);
			} else if (acc.state == CheckinHandler.IS_CHECKED) {
				dataBase.updataOne(acc);
			} else {
				success = false;
			}
		}
		D.e("CheckinService : Checkin End , success is " + success
				+ " , points is " + pointsManager.queryPoints());
		if (success) {
			spf.saveLastCheck();
			sendTipBroadcast();
		}
	}

	private void sendTipBroadcast() {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		intent.setAction(CheckinActivity.ACTION_TIP_RECEIVER);
		intent.putExtra("success", true);
		sendBroadcast(intent);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		D.d(TAG, "-----onDestroy-----");
		isRun = false;
		super.onDestroy();
	}

}
